package org.example.forum.service.impl;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.example.forum.common.AppResult;
import org.example.forum.common.ResultCode;
import org.example.forum.common.StringUtils;
import org.example.forum.dao.BoardMapper;
import org.example.forum.dao.ArticleMapper;
import org.example.forum.dao.UserMapper;
import org.example.forum.exception.ApplicationException;
import org.example.forum.model.Article;
import org.example.forum.model.Board;
import org.example.forum.model.User;
import org.example.forum.service.IArticleService;

import org.example.forum.service.IBoradService;
import org.example.forum.service.IUserService;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
@Service
@Slf4j
public class ArticleServiceImpl implements IArticleService {
    @Resource
    private ArticleMapper articleMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private BoardMapper boardMapper;
    @Resource
    private IBoradService boradService;
    @Resource
    private IUserService userService;

    @Override
    public List<Article> selectAll() {
        return articleMapper.selectAll();
    }

    @Override
    public List<Article> selectByBoardId(Long boardId) {
        if (boardId == null || boardId <= 0) {
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }

        return articleMapper.selectAllByBoardId(boardId);
    }

    @Override
    public void create(Article article) {
        if (article == null || StringUtils.isEmpty(article.getContent()) || StringUtils.isEmpty(article.getTitle()) ||
                article.getUserId() == null) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Date now = new Date();
        article.setCreateTime(now);
        article.setUpdateTime(now);
        article.setVisitCount(0); // 访问数
        article.setReplyCount(0); // 回复数
        article.setLikeCount(0);  // 点赞数
        article.setDeleteState((byte) 0);
        article.setState((byte) 0);
        int row = articleMapper.insertSelective(article);
        if (row != 1) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        User user = userMapper.selectByPrimaryKey(article.getUserId());
        if (user == null) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount() + 1);
        int row1 = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row1 != 1) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        Board board = boardMapper.selectByPrimaryKey(article.getBoardId());
        if (board == null) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        board.setArticleCount(board.getArticleCount() + 1);
        row = boardMapper.updateByPrimaryKeySelective(board);
        if (row != 1) {
            log.warn("系统出问题了");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public List<Article> selectByUserId(Long userId) {
        if (userId == null || userId <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 校验用户是否存在
        User user = userMapper.selectByPrimaryKey(userId);
        if (user == null) {
            // 打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString() + ", user id = " + userId);
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        // 调用DAO
        List<Article> articles = articleMapper.selectByUserId(userId);
        // 返回结果
        return articles;
    }

    @Override
    public Article selectDetailById(Long id) {
        if (id == null || id <= 0) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article article = articleMapper.selectDetailById(id);
        if (article == null) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_NOT_EXISTS));
        }
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setVisitCount(article.getVisitCount() + 1);
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1) {
            throw new ApplicationException(AppResult.failed());

        }
        article.setVisitCount(article.getVisitCount() + 1);
        return article;

    }

    @Override
    public void modify(Long id, String title, String content) {
        if (id == null || id <= 0 || StringUtils.isEmpty(title) || StringUtils.isEmpty(content)) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        Article updateArticle = new Article();
        updateArticle.setId(id);

        updateArticle.setTitle(title);
        updateArticle.setContent(content);
        Date now = new Date();
        updateArticle.setUpdateTime(now);
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);

        if (row != 1) {
            log.info("{}articleId = {}", ResultCode.ERROR_SERVICES.toString(), id);
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public Article selectById(Long id) {
        if (id == null || id <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 调用DAO
        Article article = articleMapper.selectByPrimaryKey(id);
        // 返回结果
        return article;
    }

    @Override
    public void thumbsUpById(Long id) {
        // 非空校验
        if (id == null || id <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 获取帖子详情
        Article article = articleMapper.selectByPrimaryKey(id);
        // 帖子不存在
        if (article == null || article.getDeleteState() == 1) {
            // 打印日志
            log.warn(ResultCode.FAILED_NOT_EXISTS.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_NOT_EXISTS));
        }
        // 帖子状态异常
        if (article.getState() == 1) {
            // 打印日志
            log.warn(ResultCode.FAILED_NOT_EXISTS.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
        // 构造要更新的对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setLikeCount(article.getLikeCount() + 1);
        updateArticle.setUpdateTime(new Date());

        // 调用DAO
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1) {
            // 打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }

    }

    @Override
    public void subOneArticleCountById(Long id) {
        if (id == null || id <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 根据Id查询帖子信息
        Article article = articleMapper.selectByPrimaryKey(id);
        if (article == null || article.getDeleteState() == 1) {
            // 打印日志
            log.warn(ResultCode.FAILED_NOT_EXISTS.toString() + ", article id = " + id);
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_NOT_EXISTS));
        }
        // 构造一个更新对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setDeleteState((byte) 1);
        // 调用DAO
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1) {
            // 打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        // 更新版块中的帖子数量
        boradService.subOneArticleCountById(article.getBoardId());
        // 更新用户发帖数
        userService.subOneArticleCountById(article.getUserId());
        log.info("删除帖子成功, article id = {}, user id = {}.", article.getId(), article.getUserId());
    }

}
